/*
 * Copyright (C) 2012 Virglinio & Asociados
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.virglinio.movimientocuerpo.bluetooh;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

import com.virglinio.movimientoCuerpo.opengl.EulerAngle;

public class BluetoothEulerParser extends Thread {

	/**
	 * Set to true to add debugging code and logging.
	 */
	private static final boolean DEBUG = false;

	/**
	 * The tag we use when logging, so that our messages can be distinguished
	 * from other messages in the log. Public because it's used by several
	 * classes.
	 */
	private static final String TAG = "BluetoothEulerParser"; 

	private BluetoothDevice bluetoothDevice;
	private EulerAngle eulerAngle;
	private boolean finish = false;
	private boolean connected = false;

	public BluetoothEulerParser(BluetoothDevice bluetoothDevice, EulerAngle eulerAngles) {
		// TODO Auto-generated constructor stub
		this.bluetoothDevice = bluetoothDevice;
		this.eulerAngle = eulerAngles;
	}

	private static final int AVAILBUFFERLENGTH = 1024;

	@Override
	public void run() {

		setName("BluetoothConnection" + bluetoothDevice.getAddress());

		if (DEBUG) {
			Log.e(TAG, "run BluetoothEulerParser");
		}

		try {
			// just to make sure (as recommended by the documentation)
			BluetoothAdapter.getDefaultAdapter().cancelDiscovery();			
			BluetoothSocket bluetoothSocket = null;
			Method method;
			try {
				method = bluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
				bluetoothSocket = (BluetoothSocket) method.invoke(bluetoothDevice, 1);

			} catch (SecurityException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (NoSuchMethodException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			
			bluetoothSocket.connect();
			connected = true;
			
			InputStream inputStream = bluetoothSocket.getInputStream();
			
			//DataInputStream dataInputStream = new DataInputStream(inputStream); 

			byte [] buffer = new byte[AVAILBUFFERLENGTH];
			int bytes;
			
			while(!finish) {

				if (DEBUG) {
					Log.e(TAG, "while infinito");
				}
				/*
				bytes = inputStream.read(buffer);
				eulerAngle.write(buffer, bytes);
				String a = buffer.toString();
				a = "";
				*/

				/*
				if ( EulerAngle.parseLine(dataInputStream.readLine(), eulerAngle) == null ) {
				//if ( EulerAngle.parseLine(dataInputStream.readLine(), eulerAngles) == null ) {
					if (DEBUG) {
						Log.e(TAG, "+++ IF +++");
					}
					// if the line could not be read, try again
				} else {
					// line successfully read - clear up buffer to make sure no lag is generated
					int availableBytes = dataInputStream.available();
					dataInputStream.read(availableBuffer, 0, availableBytes > AVAILBUFFERLENGTH ? AVAILBUFFERLENGTH:availableBytes);
					if (DEBUG) {
						Log.e(TAG, "+++ ELSE +++");
					}
				}
				*/
			}

			if (DEBUG) {
				Log.e(TAG, "finish run BluetoothEulerParser");
			}

			//dataInputStream.close();
			inputStream.close();
			bluetoothSocket.close();

		} catch (IOException e) {
			//BodyActivity.singleton.setText("Lost connection to " + m_device.getName());
		} finally {
			connected = false;
		}
	}

	public boolean isConnected() {
		return connected;
	}

	public void requestExitAndWait() {
		finish = true;
		try{
			join(5000);
		} catch(InterruptedException e) {
		}
	}       

	public String getDeviceName() {
		return bluetoothDevice.getName() + " (" + bluetoothDevice.getAddress() + ")";
	}
}